import { JSONCodec, NatsConnection } from "nats";
import { mnetMsg } from "../../typeDef";
import { makeForwardSubjectName } from "../forwardUtils";
import { mnetForwardSenderInterface } from "../mnetForwardSenderInterface";

const sc = JSONCodec<mnetMsg>()

export class mnetNatsSender implements mnetForwardSenderInterface {
 constructor(
        conn:NatsConnection,
        defaultTimeout:number
    ) {
        this.mConn = conn 
        this.mDefaultTimeout = defaultTimeout
    }

    //Publish a notification
    notify(readerName:string,msgName:string,msg:mnetMsg):void {
        this.mConn.publish(makeForwardSubjectName(readerName,msgName), sc.encode(msg))
    }

    //Publish a request
    async request(readerName:string,msgName:string,msg:mnetMsg):Promise<mnetMsg> {
        var subject = makeForwardSubjectName(readerName,msgName)
        const response = await this.mConn.request(
            subject, 
            sc.encode(msg),
            { timeout: this.mDefaultTimeout }
        )
    
        // 解码验证响应
        const decoded = sc.decode(response.data)
        return decoded;
    }
        
    private mConn:NatsConnection
    private mDefaultTimeout:number
}